<template>
  <view class="page-news">
    <!-- #ifdef MP-QQ -->
    <scroll-view class="listview" style="flex: 1;" enableBackToTop="true" scroll-y>
      <view v-for="(item, index) in dataList" :key="item.id">
        <news-item :newsItem="item" @close="closeItem(index)" @click="goDetail(item)"></news-item>
      </view>
      <view class="loading-more" v-if="isLoading || dataList.length > 4">
        <text class="loading-more-text">{{loadingText}}</text>
      </view>
    </scroll-view>
    <!-- #endif -->
    <!-- QQ multipleSlots=true bug -->
    <!-- #ifndef MP-QQ -->
    <uni-list class="listview" :enableBackToTop="true" :scroll-y="true">
      <uni-refresh class="refresh" @refresh="onrefresh" @pullingdown="onpullingdown" :display="refreshing ? 'show' : 'hide'">
        <div class="refresh-view">
          <image class="refresh-icon" :src="refreshIcon" :style="{width: (refreshing || pulling) ? 0: '32px'}" :class="{'refresh-icon-active': refreshFlag}"></image>
          <uni-load-more v-if="refreshing" class="loading-icon" status="loading" :contentText="loadingMoreText"></uni-load-more>
          <text class="loading-text">{{refreshText}}</text>
        </div>
      </uni-refresh>
      <uni-cell v-for="(item, index) in dataList" :key="item.id">
        <news-item :newsItem="item" @close="closeItem(index)" @click="goDetail(item)"></news-item>
      </uni-cell>
      <uni-cell v-if="isLoading || dataList.length > 4">
        <view class="loading-more">
          <text class="loading-more-text">{{loadingText}}</text>
        </view>
      </uni-cell>
    </uni-list>
    <!-- #endif -->
    <no-data class="no-data" v-if="isNoData" @retry="loadMore"></no-data>
  </view>
</template>

<script>
  import Api from '@/api/main'
  import {
    friendlyDate
  } from '@/common/utils';

  import uniList from '@/components/uni-list.vue';
  import uniCell from '@/components/uni-cell.vue';
  import uniRefresh from '@/components/uni-refresh.vue';
  import uniLoadMore from '@/components/uni-load-more.vue';
  import noData from '@/components/nodata.vue';
  import newsItem from './news-item.vue';

  export default {
    components: {
      uniList,
      uniCell,
      uniRefresh,
      uniLoadMore,
      noData,
      newsItem
    },
    props: {
      nid: {
        type: [Number, String],
        default: ''
      }
    },
    data() {
      return {
        ym: 1,
        dataList: [],
        navigateFlag: false,
        pulling: false,
        refreshing: false,
        refreshFlag: false,
        refreshText: "",
        isLoading: false,
        loadingText: '加载中...',
        isNoData: false,
        pulling: false,
        angle: 0,
        loadingMoreText: {
          contentdown: '',
          contentrefresh: '',
          contentnomore: ''
        },
        refreshIcon: ""
      }
    },
    created() {
      this.pullTimer = null;
      this.requestParams = {
        columnId: this.nid,
        minId: 0,
        pageSize: 10,
        column: 'id,post_id,title,author_name,cover,published_at,comments_count'
      };
    },
    methods: {
      async getLbMainData({ lbid, ym }) {
        const list = await this.$http.post(Api.getLbMainData, { lbid, ym })
        if (list) {
          this.dataList = this.dataList.concat(list)
        }
      },
      async loadData(refresh) {
        console.log('loadData', refresh);
        if (this.isLoading) {
          return;
        }

        this.isLoading = true;
        this.isNoData = false;
        this.requestParams.time = new Date().getTime() + '';

        var startTime = new Date();

        this.$http.post(Api.getLbMainData, { lbid: this.nid, ym: this.ym })
          .then(list => {
            var endTime = new Date();
            console.log("request time " + new Date(endTime - startTime).getTime());
            this.isNoData = (list <= 0);

            if (refresh) {
              this.dataList = list || [];
            } else {
              this.dataList = this.dataList.concat(list || []);
            }
            this.isLoading = false;
          })
          .catch(err => {
            if (this.dataList.length == 0) {
              this.isNoData = true;
            }
            this.isLoading = false;
          })
        // uni.request({
        //   // url: this.$host + 'api/news',
        //   url: 'https://unidemo.dcloud.net.cn/api/news',
        //   data: this.requestParams,
        //   success: (result) => {
        //     var endTime = new Date();
        //     console.log("request time " + new Date(endTime - startTime).getTime());
        //     const data = result.data;
        //     this.isNoData = (data.length <= 0);

        //     const data_list = data.map((news) => {
        //       return {
        //         id: this.newGuid() + news.id,
        //         newsid: news.id,
        //         article_type: 1,
        //         datetime: friendlyDate(new Date(news.published_at.replace(/\-/g,
        //           '/')).getTime()),
        //         title: news.title,
        //         image_url: news.cover,
        //         source: news.author_name,
        //         comment_count: news.comments_count,
        //         post_id: news.post_id
        //       };
        //     });

        //     if (refresh) {
        //       this.dataList = data_list;
        //       this.requestParams.minId = 0;
        //     } else {
        //       this.dataList = this.dataList.concat(data_list);
        //       this.requestParams.minId = data[data.length - 1].id;
        //     }
        //   },
        //   fail: (err) => {
        //     console.log(err);
        //     if (this.dataList.length == 0) {
        //       this.isNoData = true;
        //     }
        //   },
        //   complete: (e) => {
        //     this.isLoading = false;
        //     if (refresh) {
        //       this.refreshing = false;
        //       this.refreshFlag = false;
        //       this.refreshText = "已刷新";
        //       if (this.pullTimer) {
        //         clearTimeout(this.pullTimer);
        //       }
        //       this.pullTimer = setTimeout(() => {
        //         this.pulling = false;
        //       }, 1000);
        //     }
        //   }
        // });
      },
      loadMore(e) {
        console.log('loadMore');
        this.loadData();
      },
      clear() {
        this.dataList.length = 0;
        this.requestParams.minId = 0;
      },
      goDetail(detail) {
        if (this.navigateFlag) {
          return;
        }
        this.navigateFlag = true;
        uni.navigateTo({
          url: '/pages/detail/detail?query=' + encodeURIComponent(JSON.stringify(detail))
        });
        setTimeout(() => {
          this.navigateFlag = false;
        }, 200)
      },
      closeItem(index) {
        uni.showModal({
          content: '不感兴趣？',
          success: (res) => {
            if (res.confirm) {
              this.dataList.splice(index, 1);
            }
          }
        })
      },
      refreshData() {
        console.log('refreshData', refreshData);
        if (this.isLoading) {
          return;
        }
        this.pulling = true;
        this.refreshing = true;
        this.refreshText = "正在刷新...";
        this.loadData(true);
      },
      onrefresh(e) {
        console.log('onrefresh', e);
        this.refreshData();
      },
      onpullingdown(e) {
        if (this.refreshing) {
          return;
        }

        // var angle = (e.pullingDistance) / e.viewHeight * 180;
        // if (angle > 180) {
        // 	angle = 180;
        // }
        // tab.angle = angle;

        this.pulling = false;
        if (Math.abs(e.pullingDistance) > Math.abs(e.viewHeight)) {
          this.refreshFlag = true;
          this.refreshText = "释放立即刷新";
        } else {
          this.refreshFlag = false;
          this.refreshText = "下拉可以刷新";
        }
      },
      newGuid() {
        let s4 = function () {
          return (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
        }
        return (s4() + s4() + "-" + s4() + "-4" + s4().substr(0, 3) + "-" + s4() + "-" + s4() + s4() + s4()).toUpperCase();
      }
    }
  }
</script>

<style scoped>
  .no-data {
    flex: 1;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
  }

  .page-news {
    flex: 1;
    flex-direction: column;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }

  .listview {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    /* #ifndef APP-NVUE */
    display: flex;
    flex-direction: column;
    /* #endif */
    /* #ifndef MP-ALIPAY */
    flex-direction: column;
    /* #endif */
  }

  .refresh {
    justify-content: center;
  }

  .refresh-view {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    width: 750rpx;
    height: 64px;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: center;
  }

  .refresh-icon {
    width: 32px;
    height: 32px;
    transition-duration: .5s;
    transition-property: transform;
    transform: rotate(0deg);
    transform-origin: 15px 15px;
  }

  .refresh-icon-active {
    transform: rotate(180deg);
  }

  .loading-icon {
    width: 28px;
    height: 28px;
    margin-right: 5px;
    color: gray;
  }

  .loading-text {
    margin-left: 2px;
    font-size: 16px;
    color: #999999;
  }

  .loading-more {
    align-items: center;
    justify-content: center;
    padding-top: 14px;
    padding-bottom: 14px;
    text-align: center;
  }

  .loading-more-text {
    font-size: 28upx;
    color: #999;
  }
</style>